
import requests
import json
import time
import re
import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(levelname)s - %(message)s')


class NineZeroGoSign:
    def __init__(self,username,password):
        ##初始化类中私有属性
        self.__username = username
        self.__password = password
        self.__fromUserName = ""
        self.__cookie = ""
        self.__session = requests.session()
        self.__LoginUrl = "https://m.veding.com/app/buyer/account/login.jhtml"
        self.__AuthUrl = "https://m.veding.com/wx/auth/login.jhtml?"
        self.__SignWebUrl = "https://m.veding.com/wx/customer/sign/index.wx"
        self.__SignBtnUrl = "https://m.veding.com/wx/customer/signin.wx"
        self.__form = {
            "userName": self.__username,
            "password": self.__password,
            "uid": "95626",
            "userClientId": ""
        }
        self.__params = {
            "id": "87652",
            "userId": "95626",
            "firstShop": "Y",
            "gotoUrl": "/wx/weimei/customer/index.wx?ftTemplateId=27868&iconIndex=3",
            "fromWechatAuth": "Y",
            "clientInitURL": "Y",
            "fromApp": "Y",
        }
        self.__headers = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Mobile Safari/537.36 Edg/85.0.564.44",
            "X-Requested-With": "XMLHttpRequest"
        }
    ##登录获取fromUserName
    def GetFromUserName(self):
        while True:
            res = requests.post(url=self.__LoginUrl,data=self.__form)
            if res.status_code == 200:
                logging.info("获取FromUserName"+res.text)
                resJson = json.loads(res.text)
                if resJson["ret"] == 1:
                    logging.warning("账号错误")
                    quit()
                elif resJson["ret"] == 2:
                    logging.warning("密码错误")
                    quit()
                else:
                    if resJson["u"] != "":
                        logging.info("获取FromUserName成功,等待5秒")
                        self.__fromUserName = resJson["u"]
                        self.__params["fromUserName"] = self.__fromUserName
                        time.sleep(5)
                        break
                    else:
                        continue
            else:
                logging.warning("获取FromUserName失败")
    def GetCookie(self):
        while True:
            res = self.__session.get(url = self.__AuthUrl,
                                     params = self.__params,
                                     headers = self.__headers)
            if res.status_code == 200:
                ##获取响应标头的set-cookie
                ##session.cookies是CookieJar类型,requests.utils.dict_from_cookiejar可以把cookiejar类型转换成dict类型
                set_cookie = requests.utils.dict_from_cookiejar(self.__session.cookies)
                logging.info("获取set-cookie"+str(set_cookie))
                for i in set_cookie:
                    self.__cookie += i + "=" + set_cookie[i] + ";"
                self.__cookie = self.__cookie[:-1]
                logging.info("已整理cookie,等待5秒")
                self.__headers["Cookie"] = self.__cookie
                time.sleep(5)
                break
            else:
                logging.warning("获取cookie失败")
                continue
    ##签到
    def Sign(self):
        while True:
            ##进入签到页面
            signweb = self.__session.get(url = self.__SignWebUrl,
                                         headers = self.__headers)
            if signweb.status_code == 200:
                logging.info("进入签到页面，等待3秒")
                time.sleep(3)
                signweb.encoding == "utf-8"
                signwebtext = signweb.text
                if "当前链接已失效，请重新进入" in signwebtext:
                    logging.warning("Cookie失效")
                    continue
                elif "未签到" in signwebtext:
                    logging.info("今日未签到")
                    totalSignCount = re.findall('<a class="id" id="totalSigninCount">(.*?)</a>',signwebtext)[0]
                    signday = re.findall('已连续签到 (.*?) 天', signwebtext)[0]
                    ##签到请求
                    sign = self.__session.get(url = self.__SignBtnUrl,
                                              headers = self.__headers)
                    if sign.status_code == 200:
                        logging.info("签到成功")
                        msg = "签到成功"
                    else:
                        logging.warning("签到错误")
                    logging.info("累计签到天数:"+totalSignCount + " +1")
                    logging.info("已连续签到天数:"+signday + " +1")
                    int(signday) += 1
                    break
                elif "已签到" in signwebtext:
                    logging.info("今日已签到")
                    totalSignCount = re.findall('<a class="id" id="totalSigninCount">(.*?)</a>',signwebtext)[0]
                    signday = re.findall('已连续签到 (.*?) 天', signwebtext)[0]
                    logging.info("累计签到天数:"+totalSignCount)
                    logging.info("已连续签到天数:"+signday)
                    msg = "今日已签到"
                    break
            else:
                logging.warning("进入签到页面错误")
                continue
        return signday,msg

    def sendServerChan(self,msg):
        KEY = ''  # 此处替换为你自己的KEY，在Qmsg酱官网登录后，在控制台可以获取KEY
        if '签到成功' in str(msg):
            data = {
                "msg": msg,  # 需要发送的消息
                "qq": ""  # 需要接收消息的QQ号码
            }
        else:
            data = {
                "msg": msg,  # 需要发送的消息
                "qq": ""  # 需要接收消息的QQ号码
            }
        url='https://qmsg.zendee.cn/send/'+KEY  #私聊消息推送接口
        response = requests.post(url,data=data)

def main():
    try:
        ##初始化类的属性
        s = NineZeroGoSign("username","password")
        s.GetFromUserName()
        s.GetCookie()
        result =  s.Sign()
        notice = "7770" + result[1] + "，累计签到天数:" + result[0]
        print(notice)
        s.sendServerChan(notice)
    except Exception as error:
        logging.warning("运行错误:" + error)

    try:
        ##初始化类的属性
        s = NineZeroGoSign("username","password")
        s.GetFromUserName()
        s.GetCookie()
        result =  s.Sign()
        notice = "1310" + result[1] + "，累计签到天数:" + result[0]
        print(notice)
        s.sendServerChan(notice)
    except Exception as error:
        logging.warning("运行错误:" + error)

# 阿里云的入口函数
def handler(event, context):
    main()

if __name__ == "__main__":
    main()



